import { Component, ViewEncapsulation } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormBuilder, FormGroup, Validator, Validators } from '@angular/forms';
import { Router } from '@angular/router';

import { phoneNumberValidator } from 'utils/index';
import { ApiRequest } from 'service/ApiRequest';

@Component({
    selector: 'findback',
    encapsulation: ViewEncapsulation.Emulated,
    templateUrl: './ValidateTel.html',
    styleUrls: []
  }
)

export class ValidateTelComponent {
  //loading
  private loading: boolean = false;
  //手机号是否被注册
  private phoneNumberUsed: boolean = true;
  //验证码倒计时
  private countTime: number = 0;
  //后端错误
  private error: string = '';

  public validateTelForm:FormGroup;

  constructor(private formBuilder:FormBuilder, private router: Router, private apiRequest:ApiRequest) {

  }

  ngOnInit() {
    this.validateTelForm = this.formBuilder.group({
      PhoneNumber:[null, Validators.compose([Validators.required, phoneNumberValidator])],
      VerificationCode: [null, Validators.compose([Validators.required])],
    });
  }

  isPhoneNumberUsed(){
    if(!this.validateTelForm.controls.PhoneNumber.errors){
      this.apiRequest.isPhoneNumberUsed(this.validateTelForm.value.PhoneNumber).then((data) => {
        this.phoneNumberUsed = data;
      });
    }
  }

  requestVerificationCodeForResetPassword() {
    let self = this;
    this.apiRequest.requestVerificationCodeForResetPassword(this.validateTelForm.value.PhoneNumber).then((data) => {
      self.countTime = 60;
      let count = setInterval(function(){
        if(self.countTime > 0){
          self.countTime --;
        } else if (self.countTime === 0) {
          clearInterval(count);
        }
      },1000);
    });
  }

  // 清除输入框内容
  clear(key) {
    const value = this.validateTelForm.value;
    value[key] = '';
    this.validateTelForm.setValue(value);
  }

  async validateTel() {
    if(this.validateTelForm.valid && this.phoneNumberUsed){
      this.loading = true;
      await this.apiRequest.validateVerificationCodeForResetPassword(this.validateTelForm.value).then((data) => {
        this.loading = false;
        if(data){
          this.router.navigate(['/index/login/findpwd/resetpwd', { phoneNumber: this.validateTelForm.value.PhoneNumber }]);
        } else {
          this.error = '验证码错误或失效';
        }
      }).catch((e) => {
        this.loading = false;
      });
    }
  }

}
